import pymysql
from industryClassLib import liandoIndustryClass3ToPathDict

class getMysqlDataBigData():
    def __init__(self):
        # mysql数据库连接
        self.connection = pymysql.connect(
            host='10.0.2.87',
            port=3506,
            user='root',
            password='bigdata#2020BD7165',
            database='liando_bi',
            connect_timeout=36000
        )
        self.cursor = self.connection.cursor()

    # 企业唯一ID号
    def getCompanyCreditCode(self, companyName):
        try:
            query = "SELECT credit_code FROM total_company_list WHERE company_name = %s"
            self.cursor.execute(query, (companyName,))
            result = self.cursor.fetchone()
            if result:
                return result[0] if result[0] else ""  # 返回credit_code
            else:
                return ""
        except Exception as e:
            print(f"[ERROR]getMysqlDataBigData查询错误: {e}")
            return ""

    # 获取企业经营范围、国民行业、自建行业
    def getIndustryClass(self, uniscid):
        try:
            query = "SELECT gm_first, gm_second, gm_third, gm_fourth, lead_flag,business_scope FROM tmp_dwd_online_final_all WHERE uniscid = %s"
            self.cursor.execute(query, (uniscid,))
            result = self.cursor.fetchone()
            if result:
                # 国民拼接成“一级|二级|三级|四级”
                gm = result[0] if result[0] else ""
                for i in range(1, 4):
                    if result[i]:
                        gm = gm + "|" + result[i]
                    else:
                        break
                # 自建返回“三级|三级|三级|...”，通过字典翻译成["一级|二级|三级", ...]
                liando = []
                if result[4]:
                    for k in result[4].split("|"):
                        if k not in liandoIndustryClass3ToPathDict:
                            print("[ERROR]getMysqlDataBigData查询错误liandoIndustryClass3ToPathDict: %s"%k)
                        else:
                            liando.append(liandoIndustryClass3ToPathDict[k])
                # 经营范围
                businessScope = ""
                if result[5]:
                    businessScope = result[5]
                return [gm, liando, businessScope]
            else:
                return ["", "", ""]
        except Exception as e:
            print(f"[ERROR]getMysqlDataBigData查询错误: {e}")
            return ["", "", ""]

    def progress(self, companyName):
        creditCode = self.getCompanyCreditCode(companyName)
        return self.getIndustryClass(creditCode)

    # 关闭游标和连接
    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()



if __name__ == "__main__":
    companyName = "成都瑶熊软件开发工作室"
    mysqlDataBigData = getMysqlDataBigData()
    r = mysqlDataBigData.getCompanyCreditCode(companyName)
    print(r)
    r = mysqlDataBigData.getIndustryClass(r)
    print(r)
